<template>
  <div class="edit-container">
    <el-form v-loading="saveLoading" ref="form" :model="form" :rules="rules" label-width="100px" @submit.native.prevent>
      <el-form-item label="封面：" prop="cover">
        <el-upload
            class="avatar-uploader"
            action
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :http-request="handleUploadForm"
            :headers="myHeaders"
            :before-upload="beforeAvatarUpload">
          <img v-if="form.cover" :src="imageUrl + form.cover" class="avatar" alt="">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="标题：" prop="title">
        <el-input v-model="form.title" placeholder="标题" maxlength="30" style="width: 300px;"></el-input>
      </el-form-item>
      <el-form-item label="类型：" prop="type">
        <el-select v-model="form.type" clearable placeholder="请选择" style="width: 300px;">
          <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.data"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="内容：" prop="content">
        <Tinymce v-model="form.content"></Tinymce>
      </el-form-item>
      <!--      <el-form-item label="状态" prop="status">-->
      <!--        <el-switch v-model="form.status" :active-value="1" :inactive-value="0"></el-switch>-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button v-loading="saveLoading" element-loading-background="rgba(0, 0, 0, 0.3)" type="primary"
                   @click="handlerSubmit" v-has-permi="['admin:notice:save']">保存
        </el-button>
        <el-button @click="close">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {save} from "@/api/notice";
import Tinymce from "@/components/Tinymce/index.vue";
import {getToken} from "@/utils/auth";
import {upload} from "@/api/upload";

export default {
  components: {Tinymce},
  props: {
    isCreate: {
      type: Number,
      required: true
    },
    editData: {
      type: Object,
      default: () => {
        return {}
      }
    },
  },
  data() {
    return {
      form: {
        id: null,
        cover: '',
        title: '',
        type: null,
        content: '',
        status: 1,
      },
      rules: {
        cover: [{required: true, message: '请上传封面', trigger: ['blur']}],
        title: [{required: true, message: '请填写标题', trigger: ['blur']}],
        type: [{required: true, message: '请现在类型', trigger: ['blur']}],
        content: [{required: true, message: '请填写内容', trigger: ['blur']}],
      },
      roles: [],
      saveLoading: false,
      formLoading: false,
      uploads: {
        show: false,
        multiple: true,
      },
      typeList: [{id: 1, data: "公告"}, {id: 2, data: "通知"}],
      myHeaders: {"token": getToken()},
      imageUrl: '',
    }
  },
  mounted() {
    this.imageUrl = process.env.VUE_APP_IMAGE_URL
    if (this.isCreate === 1) {
      this.getDetail();
    }
  },
  methods: {
    getDetail() {
      this.form = this.editData
    },
    handlerSubmit() {
      if (this.saveLoading) {
        return;
      }
      this.$refs.form.validate(valid => {
        if (!valid) return;
        this.saveLoading = true;
        save(this.form).then(() => {
          this.$message.success('保存成功');
          this.close();
        }).finally(() => {
          this.saveLoading = false
        })
      })
    },
    handleAvatarSuccess(res, file) {
      this.form.cover = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG、PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handleUploadForm(param) {
      const formData = new FormData();
      //0=>maintain 全部
      formData.append("file", param.file);
      let loading = this.$loading({
        lock: true,
        text: "上传中，请稍候...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      upload(formData)
          .then((res) => {
            this.form.cover = res
            //图片上传接口 后期调用
            loading.close();
            this.$message.success("上传成功");
          }).catch((res) => {
        loading.close();
      });
    },
    close() {
      this.$emit('hideEditDialog');
    },
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
